import 'dart:async';

import 'package:get/get.dart';

enum CountDownMode { five,fast, slow, normal }


class TimerManager {

  TimerManager._internal();

  static final TimerManager _singleton = TimerManager._internal();

  factory TimerManager() => _singleton;

  Timer? _timer;
  RxnInt fastTime = RxnInt(-1);
  RxnInt normalTime = RxnInt(-1);
  RxnInt slowTime = RxnInt(-1);
  RxnInt fiveTime = RxnInt(3);

  int? fastCountdown;
  int? slowCountdown;
  int? normalCountdown;
  int? fiveCountdown = 3;

  void setCountDownTime({int? fastCountdown,int? slowCountdown,int? normalCountdown,}){
    this.fastCountdown = fastCountdown;
    this.slowCountdown = slowCountdown;
    this.normalCountdown = normalCountdown;
  }


  void startCountDown(CountDownMode mode,callback,{bool reset = true}){
    if(_timer != null){
      if (_timer!.isActive) {
        _timer!.cancel();
        _timer = null;
      }
    }
    int countTime = 0;
    if(reset){
      if(mode == CountDownMode.five){
        countTime = fiveCountdown??3;
      }
      if(mode == CountDownMode.fast){
        countTime = fastCountdown??30;
      }
      if(mode == CountDownMode.normal){
        countTime = normalCountdown??120;
      }
      if(mode == CountDownMode.slow){
        countTime = slowCountdown??300;
      }
      setTime(mode,countTime);
    }else{
      if(mode == CountDownMode.five){
        countTime = fiveTime.value??3;
      }
      if(mode == CountDownMode.fast){
        countTime = fastTime.value??30;
      }
      if(mode == CountDownMode.normal){
        countTime = normalTime.value??120;
      }
      if(mode == CountDownMode.slow){
        countTime = slowTime.value??300;
      }
    }
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countTime <= 0) {
        callback();
        _timer?.cancel();
        _timer = null;
        return;
      }
      countTime--;
      setTime(mode,countTime);
      print('mode = ${mode} ,countTime=${countTime}');
    });
  }

  setTime(mode, countTime){
    if(mode == CountDownMode.five){
      fiveTime.value = countTime;
    }
    if(mode == CountDownMode.fast){
      fastTime.value = countTime;
    }
    if(mode == CountDownMode.normal){
      normalTime.value = countTime;
    }
    if(mode == CountDownMode.slow){
      slowTime.value = countTime;
    }
  }

  void cancel(){
    if(_timer != null){
      if (_timer!.isActive) {
        _timer!.cancel();
        _timer = null;
      }
    }
  }

}
